#include <stdio.h>
#include <pthread.h>
#include <SkypeAPI-Carbon.h>
#include <Foundation/NSAutoreleasePool.h>

// gcc -g -fPIC -Wall skypectl.c -o skypectl -F/usr/local/src/skypectl/ -framework Skype -ISkype.framework/Headers/ -framework Carbon -lpthread -fconstant-cfstrings -ObjC -framework Foundation

typedef void (*sighandler_t)(int);

void handle_signal(int signo)
{
    fflush(stdout);
}

void
MySkypeNotificationReceived(CFStringRef aNotificationString)
{
    fprintf(stdout, "%s\n", CFStringGetCStringPtr(aNotificationString, 0));
}

void
MySkypeAttachResponse(unsigned int aAttachResponseCode)
{
}

void
MySkypeBecameAvailable(CFPropertyListRef aNotification)
{
    fprintf(stdout, "SKYPECTL AVAILABLE\n");
    ConnectToSkype(); 
}

void
MySkypeBecameUnavailable(CFPropertyListRef aNotification)
{
    fprintf(stdout, "SKYPECTL UNAVAILABLE\n");
    ConnectToSkype(); 
}

void
RunThread()
{
    RunApplicationEventLoop(); 
}

int
main(int argc, char **argv)
{
    struct SkypeDelegate mySkypeDelegate; 
    char *tmp = (char *)malloc(sizeof(char) * 1024);
    pthread_t tid;
    CFStringRef cmd, resp;
    char c;

    tmp[0] = '\0';
    NSAutoreleasePool* pool	= [[NSAutoreleasePool alloc] init];

    mySkypeDelegate.SkypeNotificationReceived = &MySkypeNotificationReceived; 
    mySkypeDelegate.SkypeAttachResponse = &MySkypeAttachResponse; 
    mySkypeDelegate.SkypeBecameAvailable = &MySkypeBecameAvailable; 
    mySkypeDelegate.SkypeBecameUnavailable = &MySkypeBecameUnavailable; 
    mySkypeDelegate.clientApplicationName = CFSTR("skypectl"); 

    SetSkypeDelegate(&mySkypeDelegate); 
    ConnectToSkype(); 

    pthread_create(&tid, NULL, (void *) RunThread, NULL);
    while(c != EOF) {
        c = getchar();
        switch(c) {
            case '\n': /* parse and execute. */
                if (tmp[0] != '\0') {
                    //cmd = CFStringCreateWithCString(kCFAllocatorDefault, tmp, kCFStringEncodingMacRoman);
                    cmd = CFStringCreateWithCString(kCFAllocatorDefault, tmp, kCFStringEncodingASCII);
                    fprintf(stdout, "=>%s\n", CFStringGetCStringPtr(cmd, 0));
                    resp = SendSkypeCommand(cmd);
                    CFRelease(cmd);
                    if (resp != NULL) {
                        fprintf(stdout, "%s\n", CFStringGetCStringPtr(resp, 0));
                    }
                    bzero(tmp, sizeof(tmp));
                }
                break;
            default: strncat(tmp, &c, 1);
                break;
        }
    }
    [pool release];

    return 0; 
}
